# -*- coding: utf-8 -*-
# vim:set noet ts=4:
#
# scim-python
#
# Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com>
#
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA  02111-1307  USA
#
# $Id: $
#
import scim
import gtk 
import os
import sys
import gtk.glade
import gobject
import commands
try:
	from PYDict import *
except:
	pathname = os.path.dirname (__file__)
	path = os.path.abspath(pathname)
	print path
	path = os.path.join (path, "../../engine/PinYin")
	path = os.path.abspath(path)
	print path
	sys.path.append(path)
	from PYDict import *

from gettext import dgettext
_ = lambda a : dgettext ("scim-python", a)
N_ = lambda x : x

gtk.glade.textdomain("scim-python")

shuangpin_schema_list = SHUANGPIN_SCHEMAS.keys()
pinyin_schema_list = [N_("QuanPin"),N_("JianPin"),N_("ShuangPin")]
ConfigBase = "/IMEngine/Python/ZhengJu/"
Pass = lambda get: get
Config = {
	"ShuangPinSchema" : ( lambda get: shuangpin_schema_list.index(get) ,
					lambda set: shuangpin_schema_list[set],
					"MSPY"),
	"PinYinSchema" : ( lambda get: pinyin_schema_list.index(get) ,
					lambda set: pinyin_schema_list[set],
					"JianPin"),
	"LargeCharset" :( Pass, Pass, False),
	"CreateUserWords" :( Pass, Pass, True),
	"CreateUserPhrases" :( Pass, Pass, True),
	"AdjustWordFreq" :( Pass, Pass, True),
	"ProgressivePrompt" : ( Pass, Pass, True),
	"LogConvError": ( Pass, Pass, True),
	"SplitPinyin":  ( Pass, Pass, True),
	"TranslateShuangPin":  ( Pass, Pass, True),
	"MixedInput": ( Pass, Pass, True),
	"FuzzyPinyin": ( Pass, Pass, False),
	"FuzzyS_Sh": ( Pass, Pass, True),
	"FuzzyC_Ch": ( Pass, Pass, True),
	"FuzzyZ_Zh": ( Pass, Pass, True),
	"FuzzyL_N": ( Pass, Pass, True),
	"FuzzyIn_Ing": ( Pass, Pass, True),
	"FuzzyEn_Eng": ( Pass, Pass, True),
	"FuzzyAn_Ang": ( Pass, Pass, True)
}

class ZhengJuSetupUI ():

	def __init__ (self, helper_info):
		self._helper_info = helper_info
		self._helper_agent = scim.HelperAgent ()
		self.orgin_value = {}

	def _create_ui (self):
		pathname = os.path.dirname (__file__)
		path = os.path.abspath(pathname)
		self.xml = gtk.glade.XML(path+'/ZhengJuUI.glade')
		self.xml.signal_autoconnect (self)
		self.window = self.xml.get_widget ("window_main")
		
		gtk_pinin_schema = self.xml.get_widget("PinYinSchema")
		liststore = gtk.ListStore(str)
		for k in pinyin_schema_list:
			liststore.append([_(k)])
		gtk_pinin_schema.set_model(liststore)
		
		gtk_shuangpin_schema = self.xml.get_widget("ShuangPinSchema")
		liststore = gtk.ListStore(str)
		for k in shuangpin_schema_list:
			liststore.append([_(k)])
		gtk_shuangpin_schema.set_model(liststore)

		self.window.show_all ()
		
	def get_name (self):
		return _("ZhengJu")
	def on_ClearUserWords_clicked(self, button):
		import ZhengJuDB
		db = ZhengJuDB.ZhengJuDB( self.config )
		db.remove_all_user_words()
	def on_ClearAdjustedWordFreq_clicked(self, button):
		import ZhengJuDB
		db = ZhengJuDB.ZhengJuDB( self.config )
		db.remvoe_all_user_freq()
	def on_ClearUserPhrases_clicked(self, button):
		import ZhengJuDB
		db = ZhengJuDB.ZhengJuDB( self.config )
		db.remove_all_user_phrase()
	def on_SendLog_clicked(self, button):
		attach = os.path.expanduser ("~/.scim/zhengju-conv-error.log")
		os.system("gnome-open \"mailto:yufanyufan@gmail.com?subject=%s&body=%s&attach=file://%s\"" % (
			_("Conversion Error Log"),
			_("Check attachment\nIf you have any suggstion, I'm glad to hear!" )
			,attach))
		
	def on_train_clicked(self,button):
		dialog = gtk.FileChooserDialog(_("Choose A Plain Text File"),buttons=
			(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
		if dialog.run() == gtk.RESPONSE_ACCEPT:
			files = dialog.get_filenames()
		else:
			files = []
		dialog.destroy()
		for i in files:
			pathname = os.path.dirname (__file__)
			path = os.path.abspath(pathname)
			path = os.path.join (path, "../../engine/PinYin/ZhengJu.py -f ")
			result = commands.getstatusoutput("python " + path + +'"' + i + '"')
			if result[0]==0:
				message = gtk.MessageDialog(buttons=gtk.BUTTONS_OK,
					message_format = _("Train Successful"))
			else:
				message = gtk.MessageDialog(buttons=gtk.BUTTONS_OK,
					message_format = _("Train Failed"))
				message.format_secondary_text(result[1])
			message.run()
			message.destroy()

	def run (self, uuid, config, display):
		self.config = config
		self._uuid = uuid
		self._display = display
		self._init_agent ()
		self._create_ui ()
		self.load_config (config)
		gtk.main ()
		self.config.flush ()
		self._helper_agent.reload_config ()
		self._helper_agent.close_connection ()

	def load_config(self,config):
		for k, v in Config.items():
			value = config.read (ConfigBase+k, v[2])
			self.xml.get_widget(k).set_active (v[0](value))
			self.orgin_value[k] = value
	
	def save_config (self, config):
		for k, v in Config.items():
			value = v[1](self.xml.get_widget(k).get_active())
			config.write (ConfigBase+k, value)
			self.orgin_value[k] = value
	
	def query_changed (self):
		for k, v in Config.items():
			if v[1](self.xml.get_widget(k).get_active()) != self.orgin_value[k]:
				return True
		return False

	def _init_agent (self):
		fd = self._helper_agent.open_connection (self._helper_info, self._display)
		if fd >= 0:
			condition = gobject.IO_IN | gobject.IO_ERR | gobject.IO_HUP
			gobject.io_add_watch (fd, condition, self.on_agent_event)

	def _quit (self, need_confirm ):
		if self.query_changed() == False:
			gtk.main_quit ()
			return True
		else:
			dlg = gtk.MessageDialog (self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION,
						gtk.BUTTONS_YES_NO, _("Are you sure to close Python PinYin Setup without save configure?"))
			id = dlg.run ()
			dlg.destroy ()
			if id == gtk.RESPONSE_YES:
				gtk.main_quit ()
				return True
		return False

	def on_window_main_delete_event (self, widget, event):
		result = self._quit (True)
		return True
	
	def on_button_ok_clicked (self, button):
		self.save_config (self.config)
		self._quit (False)
	
	def on_button_apply_clicked (self, button):
		self.save_config (self.config)
	
	def on_button_cancel_clicked (self, button):
		self._quit (True)
	
	def on_agent_event (self, fd, condition):
		if condition == gobject.IO_IN:
			while self._helper_agent.has_pending_event ():
				self._helper_agent.filter_event ()
			return True
		elif condition == gobject.IO_ERR or condition == gobject.IO_HUP:
			gtk.main_quit ()
			return False
		
		return False

if __name__ == "__main__":
	class CC:
		def __init__ (self):
			pass

		def read (self, name, v):
			return v
		def write (self, name, v):
			pass
	helper_info = ("eebeecd7-cb22-48f4-8ced-70e42dad1a79", "", "", "", 1)
	__UUID__ = "eebeecd7-cb22-58f4-8ced-70e42dad1a79"
	ZhengJuSetupUI(helper_info).run (__UUID__, CC (), ":0.0")
	
